# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
from tracer import settings


class CosBucket:

    def __init__(self, region):
        secret_id = settings.secret_id
        secret_key = settings.secret_key
        self.region = region
        config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)

        # 获取客户端对象
        self.client = CosS3Client(config)

    def create_bucket(self, bucket):
        # 3.创建桶
        response = self.client.create_bucket(
            Bucket=bucket,
            ACL='public-read',  # private / public-read / public-read-write
        )
        # 添加跨域规则
        cors_config = {
            'CORSRule': [
                {
                    'AllowedOrigin': '*',
                    'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                    'AllowedHeader': '*',
                    'ExposeHeader': '*',
                    'MaxAgeSeconds': 500
                }
            ]
        }
        self.client.put_bucket_cors(
            Bucket=bucket,
            CORSConfiguration=cors_config
        )

    def delete_file(self, bucket, key):
        # 3.删除文件
        response = self.client.delete_object(
            Bucket=bucket,
            key=key
        )

    def delete_file_list(self, bucket, key_list):
        # 3.删除文件
        objects = {
            "Quiet": "true",
            "Object": key_list
        }
        response = self.client.delete_objects(
            Bucket=bucket,
            Delete=objects
        )

    def upload_bucket(self, bucket, filepath, filename):
        # 3.上传文件
        response = self.client.upload_file(
            Bucket=bucket,
            LocalFilePath=filepath,
            Key=filename,
        )

    def upload_bucket_from_buffer(self, bucket, file_object, key):
        # 上传文件对象
        response = self.client.upload_file_from_buffer(
            Bucket=bucket,
            Body=file_object,
            Key=key
        )
        return "https://{}.cos.{}.myqcloud.com/{}".format(bucket, self.region, key)

    def credential(self, bucket):
        """ 获取cos上传临时凭证 """

        from sts.sts import Sts

        config = {
            # 临时密钥有效时长，单位是秒（30分钟=1800秒）
            'duration_seconds': 1800,
            # 固定密钥 id
            'secret_id': settings.secret_id,
            # 固定密钥 key
            'secret_key': settings.secret_key,
            # 换成你的 bucket
            'bucket': bucket,
            # 换成 bucket 所在地区
            'region': self.region,
            # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
            # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            'allow_prefix': '*',
            # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allow_actions': [
                # "name/cos:PutObject",
                'name/cos:PostObject',
                # 'name/cos:DeleteObject',
                # "name/cos:UploadPart",
                # "name/cos:UploadPartCopy",
                # "name/cos:CompleteMultipartUpload",
                # "name/cos:AbortMultipartUpload",
                "*",
            ],

        }

        sts = Sts(config)
        result_dict = sts.get_credential()
        return result_dict
